import React, { Component } from 'react';
import {
    View,Text,StyleSheet,ScrollView,Image,TextInput,Modal
} from 'react-native';
import {NavigationActions} from 'react-navigation';
import pxToDp from '../common/comm';
import * as DATA from '../data/data';
import * as COMM from '../common/comm';

export default class Login extends Component {
    constructor(props) {
        super(props);
        this.state = {
            phone: '',
            pwd:'',
            isModal: false,
            alertTxt:''
        }
    }

    //提示框3秒后消失
    _show(txt) {
        this.setState({
            isModal: true,
            alertTxt: txt
        });
        this.timer = setTimeout(() => {this._hide()},3000);
    }

    _hide() {
        this.setState({
            isModal:false
        })
    }

    componentWillUnMount() {
        this.timer && clearTimeout(this.timer);
    }

    static navigationOptions={
        headerTintColor:'#fff',
        headerTitle: '登录',
        headerStyle: {
            backgroundColor: '#36ad50',
            height: pxToDp(110)
        },
        headerTitleStyle: {
            color: '#fff',
            fontSize: pxToDp(34)
        }
    };
    checkPhone() {
        var phone = this.state.phone; //手机号
        var pwd = this.state.pwd;
        var pattern = /^1(3|4|5|7|8)\d{9}$/; //手机号格式
        var patrn = /^(\w){6,20}$/; //密码格式
        if (phone == '') {
            this._show('请输入手机号码');
            return false;
        }
        if (!pattern.test(phone)) {
            this._show('请输入正确的手机号码');
            return false;
        }
        if (pwd == '') {
            this._show('密码不能为空');
            return false;
        }
        if (!patrn.test(pwd)) {
            this._show('请确认，密码为6-20位数字或者字母！');
            return false;
        }
        return true;
    }
    _onPress() {
        let isChecked = this.checkPhone();
        if (isChecked) {
            let _that = this;
            let data2 = 'phone=' + this.state.phone + '&pwd=' + this.state.pwd;
            fetch(DATA.LOGIN_URL, {
                method: "POST",
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: data2
            })
                .then((response) => {       // 数据解析方式
                    if (response.ok) {
                        return response.json();
                    }
                })
                .then((responseData) => {       // 获取到的数据处理
                    _that._show(responseData.msg);
                    if(responseData.status == 1){
                        const resetActions = NavigationActions.reset({
                          index: 0,
                          actions: [NavigationActions.navigate({routeName: 'Mypage'})]
                        });
                        this.props.navigation.dispatch(resetActions);

                        COMM.removeKey('loginkey');
                        COMM.saveFavoriteItem('loginkey',responseData.info.loginkey);
                    }
                })
                .catch((error) => { // 错误处理
                    _that._show('获取数据失败，请重试！');
                })
                .done();
        }
    }
    render() {
        return (
            <ScrollView
                contentContainerStyle={styles.contentContainer}
            >
                <Modal
                    animationType='fade'            // 淡入淡出
                    transparent={true}              // 透明
                    visible={this.state.isModal}    // 根据isModal决定是否显示
                    onRequestClose={() => {this.onRequestClose()}}  // android必须实现
                >
                    <View style={modalStyle.modalViewStyle}>
                        <View style={modalStyle.hudViewStyle}>
                            <Text style={modalStyle.hudTextStyle}>{this.state.alertTxt}</Text>
                        </View>
                    </View>
                </Modal>
                <Image source={{uri:DATA.ICON_IMG}} style={styles.img}></Image>
                <TextInput
                    placeholder='手机号'
                    style={[styles.input,{marginTop:pxToDp(30)}]}
                    placeholderTextColor='#ccc'
                    keyboardType='numeric'
                    underlineColorAndroid='#aaa'
                    clearButtonMode="while-editing"
                    returnKeyType="done"
                    onChangeText={(text) => {
                        this.setState({
                          phone:text
                        })
          }}
                />
                <TextInput
                    placeholder='密码(6-20位字符均可)'
                    style={styles.input}
                    keyboardType='numeric'
                    placeholderTextColor='#ccc'
                    underlineColorAndroid='#aaa'
                    secureTextEntry ={true}
                    onChangeText={(text) => {
            this.setState({
              pwd:text
            })
          }}
                />
                <Text
                    style={styles.login}
                    onPress={() => {
            this._onPress();
          }}>登录</Text>
                <View style={styles.row}>
                    <Text
                        style={styles.forget}
                        onPress={() => {
              this.props.navigation.navigate('ResetPassword');
            }}>忘记密码？</Text>
                    <Text
                        style={styles.register}
                        onPress={() => {
              this.props.navigation.navigate('Register');
            }}>注册</Text>
                </View>
            </ScrollView>
        );
    }
}
const modalStyle = StyleSheet.create({
    modalViewStyle: {
        position: 'absolute',
        top:pxToDp(900),
        alignSelf:'center'
    },
    hudViewStyle: {
        backgroundColor: 'rgba(0,0,0,0.5)',
        paddingLeft:pxToDp(15),
        paddingRight:pxToDp(15),
        paddingTop:pxToDp(10),
        paddingBottom: pxToDp(10),
        borderRadius:pxToDp(10)
    },
    hudTextStyle: {
        color:'#fff'
    }
})
var styles = StyleSheet.create({
    contentContainer: {
        backgroundColor:'#fff',
        paddingTop:pxToDp(100),
        alignItems: 'center',
        height: pxToDp(970),
    },
    img:{
        width: pxToDp(132),
        height:pxToDp(193)
    },
    input: {
        width: pxToDp(500),
        height:pxToDp(100)
    },
    login: {
        width: pxToDp(500),
        height: pxToDp(70),
        fontSize: pxToDp(36),
        backgroundColor: '#36ad50',
        color: "#fff",
        marginTop: pxToDp(30),
        textAlign: 'center',
        textAlignVertical: 'center',
        borderRadius: pxToDp(15),
    },
    row: {
        flexDirection: 'row',
        width: pxToDp(500),
        marginTop:pxToDp(15)
    },
    forget: {
        color:"#36ad50"
    },
    register: {
        position: 'absolute',
        right: pxToDp(5),
        color:'#36ad50'
    }
});